package View;
import java.io.File;
import java.io.IOException;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;



public class ClientManager {
	
	private Client clients;
	
	public ClientManager(){
		clients = null;
	}
	
	public boolean isFileExists(String fileName){
		File file = new File(fileName + ".xml");
		return file.exists();
	}
	
	public boolean createXMLFile(String fileName){
		
		if(!isFileExists(fileName)){
			try {
				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				DocumentBuilder builder;
				builder = factory.newDocumentBuilder();
				
				Document doc = builder.newDocument();
				Element rootElement = doc.createElement("CLIENTLIST");
				doc.appendChild(rootElement);
				
				Element cli = doc.createElement("CLIENT");
				
				Element user = doc.createElement("USER");
				user.appendChild(doc.createTextNode("abc"));
				cli.appendChild(user);
				
				Element password = doc.createElement("PASSWORD");
				password.appendChild(doc.createTextNode("123456"));
				cli.appendChild(password);
				
				Element exist = doc.createElement("STATE");
				exist.appendChild(doc.createTextNode("1"));
				cli.appendChild(exist);
				
				rootElement.appendChild(cli);
				
				cli = doc.createElement("CLIENT");
				
				user = doc.createElement("USER");
				user.appendChild(doc.createTextNode("efg"));
				cli.appendChild(user);
				
				password = doc.createElement("PASSWORD");
				password.appendChild(doc.createTextNode("123456"));
				cli.appendChild(password);
				
				exist = doc.createElement("STATE");
				exist.appendChild(doc.createTextNode("1"));
				cli.appendChild(exist);
				
				rootElement.appendChild(cli);
				
				//write the content into xml file
				doc.getDocumentElement().normalize();
				TransformerFactory transformerFactory = TransformerFactory.newInstance();
				Transformer transformer = transformerFactory.newTransformer();
				DOMSource src = new DOMSource(doc);
				StreamResult result = new StreamResult(fileName + ".xml");
				transformer.transform(src, result);
				
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				return false;
			} catch (TransformerConfigurationException e) {
				// TODO Auto-generated catch block
				return false;
			} catch (TransformerException e) {
				// TODO Auto-generated catch block
				return false;
			}
		}
		return true;
	}
	
	public int numberOfClients(String file){
		int sum = 0;
		File xmlFile = new File(file);	
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder;
			builder = factory.newDocumentBuilder();
			Document doc = builder.parse(xmlFile);
			doc.getDocumentElement().normalize();
			NodeList list = doc.getElementsByTagName("CLIENT");
			
			for(int i = 0; i < list.getLength(); i++){
				Node node = list.item(i);
				if(node.getNodeType() == Node.ELEMENT_NODE){
					Element element = (Element) node;
					String exist = ((Node)(element.getElementsByTagName("STATE").item(0).getChildNodes()).item(0)).getNodeValue();
					if(exist.compareTo("1") == 0)
						sum++;
				}
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sum;
	}
	
	public Vector<Client> ViewClientList(String file){
		File xmlFile = new File(file);	
		Vector<Client> clients = new Vector<Client>();
		Client cli = null;
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder;
			builder = factory.newDocumentBuilder();
			Document doc = builder.parse(xmlFile);
			doc.getDocumentElement().normalize();
			
			NodeList list = doc.getElementsByTagName("CLIENT");
			for(int i = 0; i < list.getLength(); i++){
				Node node = list.item(i);
				if(node.getNodeType() == Node.ELEMENT_NODE){
					Element element = (Element) node;
					//String ip = ((Node)(element.getElementsByTagName("IP").item(0).getChildNodes()).item(0)).getNodeValue();
					String user = ((Node)(element.getElementsByTagName("USER").item(0).getChildNodes()).item(0)).getNodeValue();
					String password = ((Node)(element.getElementsByTagName("PASSWORD").item(0).getChildNodes()).item(0)).getNodeValue();
					String exist = ((Node)(element.getElementsByTagName("STATE").item(0).getChildNodes()).item(0)).getNodeValue();
					//System.out.println(id + "\t" + name + "\t" + gender + "\t" + birthday);
					if(exist.compareTo("1") == 0){
						cli = new Client(user, password);
						clients.addElement(cli);
					}
				}
			}
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return clients;
	}
	
	public boolean AddClient(String file, Client client){
		File xmlFile = new File(file);
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder;
			builder = factory.newDocumentBuilder();
			Document doc = builder.parse(xmlFile);
			doc.getDocumentElement().normalize();
			
			Element root = doc.getDocumentElement();
			
			Element cli = doc.createElement("CLIENT");
			
			Element user = doc.createElement("USER");
			user.appendChild(doc.createTextNode(client.getUser()));
			cli.appendChild(user);
			
			Element password = doc.createElement("PASSWORD");
			password.appendChild(doc.createTextNode(client.getPassword()));
			cli.appendChild(password);
			
			Element exist = doc.createElement("STATE");
			exist.appendChild(doc.createTextNode("1"));
			cli.appendChild(exist);
			
			root.appendChild(cli);
			
			//write the content into xml file
			doc.getDocumentElement().normalize();
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource src = new DOMSource(doc);
			StreamResult result = new StreamResult(file);
			transformer.transform(src, result);
			
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}	
		return true;
	}
	
	public boolean DeleteClient(String file, String user){
		File xmlFile = new File(file);	
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder;
			builder = factory.newDocumentBuilder();
			Document doc = builder.parse(xmlFile);
			doc.getDocumentElement().normalize();
			
			NodeList list = doc.getElementsByTagName("CLIENT");
			for(int i = 0; i < list.getLength(); i++){
				Node node = list.item(i);
				if(node.getNodeType() == Node.ELEMENT_NODE){
					Element element = (Element) node;
					String userClient = ((Node)(element.getElementsByTagName("USER").item(0).getChildNodes()).item(0)).getNodeValue();
					if(userClient.compareTo(user) == 0){
						//doc.getDocumentElement().removeChild(node);
						((Node)(element.getElementsByTagName("STATE").item(0).getChildNodes()).item(0)).setNodeValue("0");
						doc.normalize();
						TransformerFactory transformerFactory = TransformerFactory.newInstance();
						Transformer transformer = transformerFactory.newTransformer();
						DOMSource src = new DOMSource(doc);
						StreamResult result = new StreamResult(file);
						transformer.transform(src, result);
						break;
					}
				}
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public int testInformation(String file, String user, String password){
		File xmlFile = new File(file);			
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(xmlFile);
			doc.getDocumentElement().normalize();
			
			NodeList list = doc.getElementsByTagName("CLIENT");
			for(int i = 0; i < list.getLength(); i++){
				Node node = list.item(i);
				if(node.getNodeType() == Node.ELEMENT_NODE){
					Element element = (Element) node;
					String userClient = ((Node)(element.getElementsByTagName("USER").item(0).getChildNodes()).item(0)).getNodeValue();
					if(userClient.compareTo(user) == 0){
						String passwordClient = ((Node)(element.getElementsByTagName("PASSWORD").item(0).getChildNodes()).item(0)).getNodeValue();
						if(passwordClient.compareTo(password) == 0){
							return 1;
						}
					}
				}
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			return 0;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			return 0;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return 0;
		}
		
		return 0;
	}
	
	public boolean UpdateClientInformation(String file, String userBefore, String userAfter, String password){
		File xmlFile = new File(file);	
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder;
			builder = factory.newDocumentBuilder();
			Document doc = builder.parse(xmlFile);
			doc.getDocumentElement().normalize();
			
			NodeList list = doc.getElementsByTagName("CLIENT");
			for(int i = 0; i < list.getLength(); i++){
				Node node = list.item(i);
				if(node.getNodeType() == Node.ELEMENT_NODE){
					Element element = (Element) node;
					String userClient = ((Node)(element.getElementsByTagName("USER").item(0).getChildNodes()).item(0)).getNodeValue();
					if(userClient.compareTo(userBefore) == 0){
						if(userAfter != null)
							((Node)(element.getElementsByTagName("USER").item(0).getChildNodes()).item(0)).setNodeValue(userAfter);
						if(password != null)
							((Node)(element.getElementsByTagName("PASSWORD").item(0).getChildNodes()).item(0)).setNodeValue(password);
						doc.normalize();
						TransformerFactory transformerFactory = TransformerFactory.newInstance();
						Transformer transformer = transformerFactory.newTransformer();
						DOMSource src = new DOMSource(doc);
						StreamResult result = new StreamResult(file);
						transformer.transform(src, result);
						break;
					}
				}
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean deleteXMLFile(String fileName){
		File file = new File(fileName);
		return file.delete();
	}
}
